import { SUBMIT_SEARCH, DEL_SEARCH_ITEM, CLEAR_ALL_SEARCH } from '../types'
import { getStore, setStore, removeStore } from '@/utils/mUtils'

const MY_SEARCH_HISTORY = 'MY_SEARCH_HISTORY'
const state = {
	searchHistory: getStore(MY_SEARCH_HISTORY)?JSON.parse(getStore(MY_SEARCH_HISTORY)):[]
}

const getters = {
	searchHistory: state => {
		return state.searchHistory
	}
}

const actions = {
	submitSearch ({commit}, keyword) {
		commit(SUBMIT_SEARCH, keyword)
	},
	delSearchItem ({commit}, item) {
		commit(DEL_SEARCH_ITEM, item)
	},
	clearSearch ({commit}) {
		commit(CLEAR_ALL_SEARCH)
	}
}

const mutations = {
	// 搜索
	[SUBMIT_SEARCH] (state, keyword) {
		let item = state.searchHistory.find(n=>n == keyword)
		if (!item) {
			state.searchHistory.push(keyword)
		}
		setStore(MY_SEARCH_HISTORY, JSON.stringify(state.searchHistory))
	},
	// 删除单条搜索记录
	[DEL_SEARCH_ITEM] (stete, item) {
		state.searchHistory.forEach((n, i) => {
			if (n == item) {
				state.searchHistory.splice(i, 1)
				setStore(MY_SEARCH_HISTORY, JSON.stringify(state.searchHistory))
			}
		})
	},
	// 清空搜索列表
	[CLEAR_ALL_SEARCH] (state) {
		state.searchHistory = []
		removeStore(MY_SEARCH_HISTORY)
	}
} 

export default {
	state,
	getters,
 	mutations,
 	actions
}